package com.wichell.framework.dfs.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wichell.framework.controller.BaseController;
import com.wichell.framework.dfs.dto.ResourceDto;
import com.wichell.framework.dfs.exception.ResourceNotFoundException;
import com.wichell.framework.dfs.exception.ResourceRequestException;
import com.wichell.framework.dfs.service.ResourceService;
import com.wichell.framework.dfs.util.ResourceUtil;

@Controller
@RequestMapping("/resource")
public class ResourceController extends BaseController {

	@Autowired
	private ResourceService resourceService;

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public List<String> uploadSysResource(@RequestParam MultipartFile[] myfilesk, HttpServletRequest request)
			throws ResourceRequestException, IOException {
		List<String> codes = new ArrayList<String>();
		for (MultipartFile mp : myfilesk) {
			codes.add(resourceService.upload(mp.getOriginalFilename(), mp.getInputStream()));
		}
		return codes;
	}

	@RequestMapping(value = "/{resourceCode}", method = RequestMethod.GET)
	public void getResource(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("resourceCode") String resourceCode) {
		byte[] content = new byte[1024];
		try {
			ResourceDto resourceDto = resourceService.download(resourceCode);
			response.setHeader("Content-Type", ResourceUtil.convertContentTypeByFileName(resourceDto.getOrignalName()));
			response.setStatus(HttpStatus.SC_OK);
			content = resourceDto.getResourceContent();
		} catch (ResourceRequestException e) {
			e.printStackTrace();
			response.setHeader("Content-Type", "text/html");
			response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			content = e.getMessage().getBytes();
		} catch (ResourceNotFoundException e) {
			e.printStackTrace();
			response.setHeader("Content-Type", "text/html");
			response.setStatus(HttpStatus.SC_NOT_FOUND);
			content = e.getMessage().getBytes();
		} finally {
			try {
				OutputStream out = response.getOutputStream();
				out.write(content);
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
